package com.android.settings.ios.general;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import androidx.fragment.app.Fragment;
import androidx.preference.PreferenceManager;

import com.android.settings.ios.R;
import com.android.settings.ios.SettingsMainActivity;

public class GeneralEditNameFragment extends Fragment {

    private EditText mEditText;
    private String mLastName = "";
    private SharedPreferences mPreferences;

    protected String mMainTitle;
    protected String mBackSubTitle;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mBackSubTitle = bundle.getString("fragment_back", null);
            mMainTitle = bundle.getString("fragment_title", getString(R.string.app_name));
        }

        mPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());

        if (bundle != null) {
            mLastName = bundle.getString("name");
        }
        if (mLastName == null || mLastName.length() == 0) {
            mLastName = mPreferences.getString("about_device_name", "");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.os_general_edit_name_fragment, null);
        mEditText = view.findViewById(android.R.id.edit);
        if (mEditText != null) {
            mEditText.setText(mLastName);
        }
        return view;
    }
    @Override
    public void onResume() {
        super.onResume();
        updateTitleIfNeeded();
    }

    protected void updateTitleIfNeeded() {
        Activity activity = getActivity();
        if (activity instanceof SettingsMainActivity) {
            activity.setTitle(mMainTitle);
            ((SettingsMainActivity) activity).setLeftBackText(mBackSubTitle);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mEditText != null) {
            String result = mEditText.getText().toString();
            if (result.length() > 0 && !result.equals(mLastName)) {
                mPreferences.edit().putString("about_device_name", result).apply();
            }
        }
    }
}
